import {
  // createAppContainer,
  createStackNavigator,
  createSwitchNavigator
} from 'react-navigation';
import {createReactNavigationReduxMiddleware, createReduxContainer} from 'react-navigation-redux-helpers';
import {connect} from 'react-redux';
import WelcomePage from "../page/WelcomePage";
import HomePage from "../page/HomePage";
import DetailPage from "../page/DetailPage";
import FetchDemoPage from "../page/FetchDemoPage";
import AsyncStorageDemoPage from "../page/AsyncStorageDemoPage";
import DataStoreDemoPage from "../page/DataStoreDemoPage";

// 欢迎页导航器
const InitNavigator = createStackNavigator({
  WelcomePage: {
    screen: WelcomePage,
    navigationOptions: {
      header: null // 禁用StackNavigator的NavigationBar
    }
  }
});

// 主页导航器
const MainNavigator = createStackNavigator({
  HomePage: {
    screen: HomePage,
    navigationOptions: {
      header: null // 禁用StackNavigator的NavigationBar
    }
  },
  DetailPage: {
    screen: DetailPage,
    navigationOptions: {
      title: '详情页'
    }
  },
  FetchDemoPage: {
    screen: FetchDemoPage,
    navigationOptions: {
      title: 'Fetch简单示例'
    }
  },
  AsyncStorageDemoPage: {
    screen: AsyncStorageDemoPage,
    navigationOptions: {
      title: 'AsyncStorage示例'
    }
  },
  DataStoreDemoPage: {
    screen: DataStoreDemoPage,
    navigationOptions: {
      title: '数据本地化示例'
    }
  }
});

// 根导航器
export const RootNavigator = createSwitchNavigator({
  Init: InitNavigator,
  Main: MainNavigator
});

// 定义默认路由为欢迎页
export const rootDom = 'Init';

// export default createAppContainer(RootNavigator);

/**
 * 初始化 react-navigation 与 redux 的中间件
 * @type {Middleware}
 */
export const navMiddleware = createReactNavigationReduxMiddleware(
  state => state.nav,
  'root'
);

/**
 * 将根导航器组件传给 createReduxContainer 函数
 * 并返回一个将navigation state 和 dispatch 函数作为 props的新组件
 * 注意：要在 createReactNavigationReduxMiddleware 函数之后执行
 * @type {React.ComponentType<*>}
 */
const AppWithNavigationState = createReduxContainer(RootNavigator, 'root');

/**
 * state到props的映射关系
 * @param state
 * @returns {{state: "react-navigation".NavigationState}}
 */
const mapStateToProps = state => ({
  state: state.nav // nav是reducer/index中合并reducer时对应的键
});

/**
 * 连接 React组件 与 Redux Store
 */
export default connect(mapStateToProps)(AppWithNavigationState);